package org.xiaojinlong.rtti;

import java.io.BufferedInputStream;
import java.util.Scanner;

/**
 * Created by jinlong on 2015/2/17.
 */
public class RTTI {
    public static void main(String[] args)
            throws ClassNotFoundException, IllegalAccessException, InstantiationException {
//        Class c = SuperToy.class;
//        System.out1.println(c.getSimpleName());
//        System.out1.println(c.getSuperclass().getSimpleName());
//        ((SuperToy) c.newInstance()).yell();
//        Class<SuperToy> cc = SuperToy.class;
//        Class<? super SuperToy> ccc = SuperToy.class.getSuperclass();
//        Class<Toy> toyType = Toy.class;
        Scanner see = new Scanner(new BufferedInputStream(System.in));
        RunningThread thread = new RunningThread(5000, BiToy.class);
        thread.run();
        while (see.hasNext()) {
            String type = see.nextLine();
            System.out.println(type);
            Class<? extends Toy> clazz = (Class<? extends Toy>)Class.forName(type);
            thread.changeType(clazz);
        }

    }
}

class RunningThread implements Runnable {
    int interval;
    Thread thread = new Thread();
    Class<? extends Toy> toyType;
    Toy toy;

    RunningThread(int interval, Class<? extends Toy> toyClass) throws IllegalAccessException, InstantiationException {
        this.interval = interval;
        this.toyType = toyClass;
        this.toy = toyType.newInstance();
    }

    void changeType(Class<? extends Toy> toyClass) throws IllegalAccessException, InstantiationException {
        toy = toyClass.newInstance();
    }

    int flag = 0;
    boolean swap() {
      if (flag == 0) {
          flag = 1;
          return true;
      } else if (flag == 1) {
          flag = 0;
          return false;
      } else
          return false;
    }

    @Override
    public void run() {
        thread.run();
        while (true) {
          toy.yell();
          try {
              Thread.sleep(interval);
              if (swap())
                  changeType(SuperToy.class);
              else
                  changeType(BiToy.class);
          } catch (InterruptedException e) {
              e.printStackTrace();
          } catch (InstantiationException e) {
              e.printStackTrace();
          } catch (IllegalAccessException e) {
              e.printStackTrace();
          }
        }
    }
}

abstract class Toy {
    abstract void yell();
}

class SuperToy extends Toy {
    @Override
    void yell() {
        System.out.println("from Super");
    }
}

class BiToy extends Toy {
    @Override
    void yell() {
        System.out.println("from Bi");
    }
}
